from django.shortcuts import render,  get_object_or_404
from django.contrib.auth.decorators import login_required
from .models  import Post, Comment
from .forms import PostForm, CommentForm
from django.shortcuts import redirect


# 帖子总览
def post_list(request):
    posts = Post.objects.all()
    return render(request, 'forum/post_list.html', {'posts': posts})


# 新增帖子
@login_required
def post_create(request):
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user  # 确保帖子作者为当前用户
            post.save()
            return redirect('forum:post_detail', pk=post.pk)
    else:
        form = PostForm()
    return render(request, 'forum/post_form.html', {'form': form})




# 单个帖子详情
def post_detail(request, pk):
    post = get_object_or_404(Post, pk=pk)
    post.views += 1
    post.save()
    comments = post.comments.all()

    if request.method == 'POST':
        comment_form = CommentForm(request.POST)
        if comment_form.is_valid():
            comment = comment_form.save(commit=False)
            comment.post = post
            comment.author = request.user
            comment.save()
            return redirect('forum:post_detail', pk=post.pk)
    else:
        comment_form = CommentForm()

    return render(request, 'forum/post_detail.html', {
        'post': post,
        'comments': comments,
        'comment_form': comment_form
    })

# 新增评论
@login_required
def add_comment(request, pk):
    post = get_object_or_404(Post, pk=pk)
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.author = request.user  # 确保评论作者为当前用户
            comment.save()
    return redirect('forum:post_detail', pk=post.pk)

# 用户个人发布帖子详情
@login_required
def user_posts(request):
    posts = Post.objects.filter(author=request.user).order_by('-created_at')
    return render(request, 'forum/user_posts.html', {'posts': posts})

# 用户个人回复帖子详情
@login_required
def user_comments(request):
    comments = Comment.objects.filter(author=request.user).order_by('-created_at')
    return render(request, 'forum/user_comments.html', {'comments': comments})


# 个人发布帖子 删除
@login_required
def delete_post(request, pk):
    post = get_object_or_404(Post, pk=pk)
    if post.author == request.user:
        post.delete()
    return redirect('forum:user_posts')

# 个人回复帖子 删除
@login_required
def delete_comment(request, pk):
    comment = get_object_or_404(Comment, pk=pk)

    if comment.author == request.user:
        comment.delete()
        return redirect('forum:user_comments')




